#!/usr/bin/env python
# Create: 2018/8/11
__author__ = '749B'

from student import models
from steed_admin import base_admin


class StudentAdmin(base_admin.ModelAdmin):
    list_display = ('name', 'status', 'alias', 'height', 'weight', 'show_id')
    list_filter = ('status',)
    filter_horizontal = ('tags', 'target')
    search_fields = ('name', 'alias')
    readonly_fields = ('alias',)
    list_per_page = 10
    actions = ('add_weight', 'set_mia', 'set_alive')

    def add_weight(self, request, queryset):
        """发现，不太适合做一个一个的修改"""
        names = []
        for item in queryset:
            obj = item.__class__.objects.get(id=item.id)
            obj.weight = str(float(item.weight) + 0.01)
            obj.save()
            names.append(item.name)
        return "%s 增加了体重" % ", ".join(names)
    add_weight.short_description = "增加体重0.01kg"

    def set_mia(self, request, queryset):
        """这里才是正确的用法：执行批量的修改"""
        queryset.update(status=2)
        return 'text-primary', '状态设置为MIA'
    set_mia.short_description = "设置为下落不明"

    def set_alive(self, request, queryset):
        """这里才是正确的用法：执行批量的修改"""
        queryset.update(status=1)
        return 'text-success', '状态设置为存活'


def upper_comment(obj):
    """被list_display应引用的方法，要写在类的外面，引用之前"""
    return obj.comment.upper()
upper_comment.short_description = '大写comment'


class PersonAdmin(base_admin.ModelAdmin):
    list_display = ('name', 'id', 'gender', 'age', 'universe', 'bounty', 'comment', upper_comment, 'comment_link')
    list_filter = ('gender', 'universe')
    search_fields = ('name', 'comment')
    list_per_page = 10
    default_actions = ()  # 把default_actions设为空，就连默认action都可以不要了

    def comment_link(self, obj):
        """被list_display应引用的方法名，写在类的里面"""
        return '-'.join(line.upper() for line in obj.comment)
    comment_link.short_description = "comment_大写分割"


class TagAdmin(base_admin.ModelAdmin):
    list_display = ('name', 'date')
    search_fields = ('name',)


base_admin.site.register(models.Student, StudentAdmin)
base_admin.site.register(models.Person, PersonAdmin)
base_admin.site.register(models.Tag, TagAdmin)


